//建立数据库连接

/*
 1.安装sequelize 并请求赋给Sequelize :类似于webform的sqlherper（像koa框架一样）;
 
 2.安装驱动(pg  pg-hstore) 给sequelize使用的工具 
  
 3.打通数据库： new一个 前面Sequelize的实例sequelize，相当于sa  类比app的创建 包含数据库名称密码等.

 4.创建表模型:  利用sequelize的define方法定义字段并交给User保管

 5.User(sequelize)把表模型更新进postgresql： User.sync({ force: true })

 6.CRUD
*/

const fs = require('fs');
const { Sequelize ,Op} = require('sequelize');
const { database, user, password, host, dialect} = require('../config/db')

const sequelize = new Sequelize(database, user, password, {
    host,
    dialect
});

//获取所有.js的文件
let files = fs.readdirSync(__dirname);

//过滤掉index.js文件
let modelfiles = files.filter(item => {
    return item.endsWith('.js') && item != 'index.js'
})

//定义一个装所有模型的对象，不定义成数组是为了以后暴露出去能快速定位
let models = {};
modelfiles.forEach(item => {
    let model = require(__dirname + '/' + item)
    modelname = item.replace('.js', '').toLowerCase();//转小写
    models[modelname] = sequelize.define(modelname, model);
});

//第二种 先同步模型暴露后再初始化模型字段
models.sync = async ()=> {
    await sequelize.sync({ force: true });
    models.users.bulkCreate([
        {
            username:'admin',
            password:'123'
        }
    ])
    models.products.bulkCreate([
        {
            name:'Soul',
            price:'188.23'
        },
        {
            name:'流星花园',
            price:'8.23'
        },
        {
            name:'凹凸曼',
            price:'18'
        },
        {
            name:'曼达星人',
            price:'0.22'
        }
    ])
}

models.Op=Op;
module.exports = models;